// pages/comment/comment.js
const { getDataNew, getStyle } = require('./posterNew.js');
import {
    getHostCommentBase,
    getHostCommentList,
    deleteHostComment,
    getHostAwardList,
    getHostReserveList,
    withDrawCommentMoney,
    replyUser,
} from '../../../api/comment.js';
import { getSceneInfo } from '../../../api/scene.js';
import { getPosterQRcode } from '../../../api/user.js';

import {
    showWxToast,
    showWxLoading,
    hideWxLoading,
} from '../../../utils/index';

let showCount = {
    comment: 10,
    award: 10,
};
let currentPage = {
    comment: 1,
    award: 1,
};
let totalPage = {
    comment: 1,
    award: 1,
};

let withDrawLock = false;
const app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        titleBarHeight: 0, // 标题栏高度
        statusBarHeight: 0, // 状态栏高度
        src: '',
        rate: 0,
        splid: '',
        labelList: [],
        avator: '',
        emcee_name: '主持人',
        theme: '婚礼主题',
        hotel_name: '场地',
        using_date: 'yyyy-mm-dd',
        xin: '0',
        pcu: '',
        comments: [],
        awards: [],
        reserves: [],
        scene: '',
        status: '',
        loading: false,
        notShareBack: true,
        qrcode: '',
        banben: '',
        canvasrendered: false,
        tabId: 0, // 0 评论 1 打赏 2 预定
        commentCount: 0,
        awardCount: 0,
        reserveCount: 0,
        reward_balance: 0,
        reward_totalsum: 0,
        showInput: false,
        album_comment_id: null,
        content: '',
        focus: true,
        isNeedUserComment: ''
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.getSystemInfo({
            success: (res) => {
                // console.log(res);
                this.setData({
                    titleBarHeight: res.model.indexOf('iPhone') !== -1 ? 44 : 48,
                    statusBarHeight: res.statusBarHeight,
                });
                // globalData.systemInfo_bottomLift = res.screenHeight - res.safeArea.bottom;
            },
            fail: (err) => {
                console.log(err);
            },
        });

        this.widget = this.selectComponent('.widget');

        if (options.scene) {
            this.setData({
                splid: options.scene,
                scene: options.scene,
            });
        }
        if (options.splid) {
            this.setData({
                splid: options.splid,
            });
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () { },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        if (this.data.notShareBack) {
            currentPage.comment = 1;
            totalPage.comment = 1;
            currentPage.award = 1;
            totalPage.award = 1;
            this.setData({
                loading: false,
                comments: [],
                awards: [],
                reserves: [],
            });
            this.getQrcode();
            this.getHostCommentBase();
            this.getHostCommentList();
            this.getHostAwardList();
            this.getHostReserveList();
        }
        this.setData({
            notShareBack: true,
        });
        this.renderToCanvas();
        this.getSceneInfo();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () { },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () { },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () { },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        let tabId = this.data.tabId;

        switch (tabId) {
            case 0:
                if (currentPage.comment < totalPage.comment) {
                    currentPage.comment++;
                    this.getHostCommentList();
                } else {
                    showWxToast('没有更多评价了 长按评价可以进行删除操作');
                }
                break;
            case 1:
                if (currentPage.award < totalPage.award) {
                    currentPage.award++;
                    this.getHostAwardList();
                } else {
                    // showWxToast("");
                }
                break;
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (e) {
        this.setData({
            notShareBack: false,
        });
        return {
            title: `${this.data.emcee_name}邀请您查看他的评价`,
            path: `/pages/index/commentShow/commentShow?splid=${this.data.splid}`,
        };
    },
    getHostCommentBase() {
        getHostCommentBase({
            splid: this.data.splid,
        })
            .then(res => {
                //
                let { splidInfo, labelList } = res.data;
                if (labelList) {
                    labelList.forEach(item => {
                        item.name = `${item.bg_name}(${item.size})`;
                    });
                }
                // ;
                this.setData({
                    labelList: res.data.labelList || [],
                    avator: splidInfo.avator,
                    emcee_name: splidInfo.emcee_name,
                    banben: splidInfo.banben,
                    theme: splidInfo.theme,
                    hotel_name: splidInfo.hotel_name,
                    using_date: splidInfo.using_date,
                    xin: res.data.xin.sf_avg,
                    pcu: splidInfo.pcu,
                    scene: splidInfo.scene,
                    status: splidInfo.status,
                });
            })
            .catch(err => { });
    },
    getHostCommentList(reload) {
        if (this.data.loading) {
            // showWxToast('加载中')
            this.setData({
                loading: true,
            });
            return;
        }
        showWxLoading('加载中');
        getHostCommentList({
            splid: this.data.splid,
            showCount: showCount.comment,
            currentPage: currentPage.comment,
        })
            .then(res => {
                hideWxLoading();
                let { list } = res.data;
                list.forEach(item => {
                    item.time = item.comment_time;
                    // item.album_comment_id = item.album_comment_id
                });

                if (reload) {
                    totalPage.comment = res.data.totalPage;
                    currentPage.comment = 1;

                    this.setData({
                        loading: false,
                        comments: list,
                        commentCount:
                            res.data.totalResult > 99 ? '99+' : res.data.totalResult,
                    });
                    this.renderToCanvas();
                } else {
                    totalPage.comment = res.data.totalPage;
                    this.setData({
                        loading: false,
                        comments: this.data.comments.concat(list),
                        commentCount:
                            res.data.totalResult > 99 ? '99+' : res.data.totalResult,
                    });
                }
            })
            .catch(err => {
                hideWxLoading();
                this.setData({
                    loading: false,
                });
            });
    },
    getHostAwardList(reload) {
        getHostAwardList({
            splid: this.data.splid,
            showCount: showCount.award,
            currentPage: currentPage.award,
        })
            .then(res => {
                let { list } = res.data;
                list.forEach(item => {
                    item.time = item.format_create_time;
                });

                if (reload) {
                    totalPage.award = res.data.totalPage;
                    totalPage.award = 1;

                    this.setData({
                        awards: list,
                        awardCount:
                            res.data.totalResult > 99 ? '99+' : res.data.totalResult,
                    });
                } else {
                    totalPage.award = res.data.totalPage;

                    this.setData({
                        awards: this.data.awards.concat(list),
                        awardCount:
                            res.data.totalResult > 99 ? '99+' : res.data.totalResult,
                    });
                }
                if (res.data.splid) {
                    let { reward_totalsum, reward_balance } = res.data.splid;
                    this.setData({
                        reward_totalsum: reward_totalsum || 0,
                        reward_balance: reward_balance || 0,
                    });
                }
            })
            .catch(err => { });
    },
    getHostReserveList() {
        getHostReserveList({
            splid: this.data.splid,
        })
            .then(res => {
                ;
                if (res.data.size > 0) {
                    let { list } = res.data;
                    list.forEach(item => {
                        item.time_interval_text = item.time_interval === '2' ? '晚宴' : '午宴';
                    });
                    this.setData({
                        reserves: list,
                        reserveCount: res.data.size,
                    });
                }
            })
            .catch(err => {
                ;
            });
    },
    change(e) {
        this.setData({
            rate: e.detail,
        });
    },
    async renderToCanvas(generatePoster) {
        // if (this.data.src) {
        //   this.svaePoster();
        //   return "";
        // }
        if (!this.data.qrcode) {
            let qrcode = await this.getQrcode();
            if (qrcode !== 'success') return;
        }
        const cusWXML = getDataNew(this.data);
        const res = await this.widget.renderToCanvas({
            wxml: cusWXML,
            style: getStyle(),
            // style,
        });
        console.log('res', res);
        this.container = res;
        this.setData({
            canvasrendered: true,
        });
        this.extraImage(generatePoster);

        // setTimeout(() => {
        //     p1.then(res => {
        //         this.container = res;
        //         this.setData({
        //             canvasrendered: true,
        //         });
        //         this.extraImage(generatePoster);
        //     });
        // }, 2000);
    },
    extraImage(generatePoster) {
        const p2 = this.widget.canvasToTempFilePath();
        p2
            .then(res => {
                this.setData({
                    src: res.tempFilePath,
                    width: this.container.layoutBox.width,
                    height: this.container.layoutBox.height,
                });
                if (generatePoster) {
                    this.svaePoster();
                }
                // this.svaePoster();
            })
            .catch(err => { });
    },

    save() {
        if (!this.data.canvasrendered) {
            showWxToast('正在准备画布中，请稍后重试');
            return;
        }

        if (this.data.src) {
            this.svaePoster();
        } else {
            this.renderToCanvas(true);
        }
    },
    backPressed(e) {
        console.log("onBackPressed");
        wx.navigateBack();
    },
    svaePoster() {
        wx.saveImageToPhotosAlbum({
            filePath: this.data.src,
            success(res) {
                wx.showModal({
                    content: '图片已保存到相册，赶紧晒一下吧~',
                    showCancel: false,
                    confirmText: '好的',
                    confirmColor: '#333',
                    success: function (res) {
                        wx.hideLoading();
                    },
                    fail: function (res) { },
                });
            },
            fail(err) {
                if (
                    err.errMsg === 'saveImageToPhotosAlbum:fail:auth denied' ||
                    err.errMsg === 'saveImageToPhotosAlbum:fail auth deny' ||
                    err.errMsg === 'saveImageToPhotosAlbum:fail authorize no response'
                ) {
                    wx.hideLoading();
                    wx.showModal({
                        title: '提示',
                        content: '需要您授权保存相册',
                        showCancel: false,
                        success: res => {
                            wx.openSetting({
                                success(settingdata) { },
                                fail(failData) { },
                                complete(finishData) { },
                            });
                        },
                    });
                }
            },
        });
    },
    sharePoster() {
        wx.previewImage({
            current: '', // 当前显示图片的http链接
            urls: [this.data.src], // 需要预览的图片http链接列表
        });
    },
    getQrcode() {
        return new Promise((resolve, reject) => {
            getPosterQRcode({
                page: 'pages/index/commentShow/commentShow',
                scene: this.data.splid,
            })
                .then(res => {
                    this.setData({
                        qrcode: res.smallProgramCode,
                    });
                    resolve('success');
                })
                .catch(err => {
                    reject('err');
                });
        });
    },
    promptDelete(e) {
        const { name, id } = e.detail;

        wx.showModal({
            // title: title,
            content: `您确认要删除${name}的评价吗`,
            cancelText: '取消',
            confirmText: '确认删除',
            success: res => {
                const { confirm } = res;

                if (confirm) {
                    this.deleteComment(id);
                } else {
                    showWxToast('取消删除');
                }
            },
            fail: () => {
                // showWxToast('确认提现')
            },
        });
    },
    deleteComment(album_comment_id) {
        deleteHostComment({
            splid: this.data.splid,
            album_comment_id,
        })
            .then(res => {
                if (res.code === 200) {
                    showWxToast('删除成功');
                    showCount.comment = 10;
                    currentPage.comment = 1;
                    totalPage.comment = 1;

                    this.setData({
                        comments: [],
                    });
                    this.data.canvasrendered = false;

                    this.getHostCommentList(true);
                } else {
                    showWxToast('删除失败');
                }
            })
            .catch(err => { });
    },
    changTabId(e) {
        let tabId = Number(e.currentTarget.dataset.id);
        this.setData({
            tabId: tabId,
        });
    },
    promptWithDraw() {
        if (this.data.reward_balance <= 0) {
            return;
        }
        wx.showModal({
            // title: title,
            content: `是否确认提现`,
            cancelText: '取消',
            confirmText: '确认提现',
            success: res => {
                const { confirm } = res;

                if (confirm) {
                    // showWxToast('确认提现')
                    this.withdraw();
                } else {
                    showWxToast('取消提现');
                }
            },
            fail: () => {
                // showWxToast('确认提现')
            },
        });
    },
    withdraw() {
        if (this.data.reward_balance <= 0.3) {
            showWxToast('提现金额需大于0.3元');
            return;
        }
        if (withDrawLock) {
            return;
        }
        withDrawLock = true;
        withDrawCommentMoney(this.data.splid)
            .then(res => {
                if (res.flag === '3') {
                    showWxToast('提现成功');
                    // 提现成功 重新获取数据
                    setTimeout(() => {
                        this.setData({
                            reward_balance: 0,
                        });
                    }, 1000);

                    withDrawLock = false;
                }
            })
            .catch(err => {
                withDrawLock = false;
                wx.showToast({
                    title: '提现失败',
                    icon: 'none',
                });
            });
    },

    replyUser(e) {
        const { album_comment_id, name, splid } = e.detail;
        this.setData({
            album_comment_id,
            showInput: true,
            focus: true,
            activeUserName: name,
        });
    },
    fetchReplyUser({ content, album_comment_id }) {
        replyUser({
            album_comment_id,
            content,
            splid: this.data.splid,
        })
            .then(res => {
                wx.showToast({
                    title: '发送成功',
                });
                setTimeout(() => {
                    this.setData({
                        comments: [],
                        content: '',
                    });
                    // this.comments =[];
                    currentPage.comment = 1;
                    totalPage.comment = 1;
                    this.resetValue();
                    this.getHostCommentList(true);
                }, 600);
            })
            .catch(err => { });
    },
    resetValue() {
        this.setData({
            activeUserName: '',
            album_comment_id: null,
            showInput: false,
        });
    },
    inputContent(e) {
        this.setData({
            content: e.detail,
        });
    },
    sendContent(e) {
        ;
        wx.showToast({
            title: e.detail,
        });
        if (!this.data.content) {
            wx.showToast({
                title: '请填写评论内容',
                icon: 'none',
            });
            return;
        }
        this.fetchReplyUser({
            content: this.data.content,
            album_comment_id: this.data.album_comment_id,
        });
    },
    getSceneInfo() {
        getSceneInfo({ splid: this.data.splid }).then((res) => {
            ;
            this.setData({
                isNeedUserComment: res.data.isNeedUserComment
            });
        }).catch((err) => {
            ;
        });
    }
});
